class WorkController < ApplicationController
  before_filter :sys_before_log

  #获取所有任务的信息
  def getWorks
    total = Work.count
    works = Work.findPage(params[:start].to_i, params[:limit].to_i)
    jsonStr="{work:"+works.to_json()+",total:"+total.to_s+"}"
    render :text => jsonStr,:layout => false
  end

  def getAllWorks
    total = Work.count
    works = Work.all
    jsonStr="{work:"+works.to_json()+",total:"+total.to_s+"}"
    render :text => jsonStr,:layout => false
  end

  def create
    begin
      work = Work.find_by_name params[:name]
      if work != nil
        info = '任务已存在，请更换！'
      else
        work = Work.new
        work.name = params[:name]
        work.save!
        info = 'success'
      end
    rescue Exception => e
      logger.info e
      info = '创建异常'
    end

    result = "{success:true,info:\"#{info}\"}"
    render :text => result,:layout => false
  end

  def delete
    begin
      ids= params[:id][1..params[:id].length-2].split(',')
      Work.destroy(ids)
      info = 'success'
    rescue Exception=>e
      logger.info e
      info = '删除异常'
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end

  def edit
    work = Work.find(params[:id])
    jsonStr = work.to_json()
    render :text=>jsonStr,:layout=>false
  end

  def update
    begin
      work = Work.find(params[:id])
      if work.name == params[:name].to_s
        info = 'success'
      else
        workUser = Work.find_by_name params[:name]
        if workUser == nil
          work.name = params[:name]
          work.save
          info = 'success'
        else
          info = '该任务已存在，请更换！'
        end
      end
    rescue Exception=>e
      logger.info e
      info = '更新异常'
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end

end
